#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
多账号管理模块
提供天翼云盘账号的增删改查功能
"""

import logging
from typing import List, Optional, Dict, Any
from datetime import datetime

from src.models.cloud import CloudAccount
from src.models.user import WebDAVUser
from src.common.database import get_session
from src.extensions.tianyi_integration import tianyi_integration

class AccountManager:
    """账号管理器"""
    
    def __init__(self):
        self.logger = logging.getLogger('AccountManager')
    
    def add_cloud_account(self, cloud_account: str, cloud_password: str, 
                         display_name: str = None, cloud_provider: str = 'tianyi') -> Optional[CloudAccount]:
        """添加云盘账号
        
        Args:
            cloud_account: 云盘账号
            cloud_password: 云盘密码
            display_name: 显示名称
            cloud_provider: 云服务提供商
        
        Returns:
            创建的账号对象，失败返回None
        """
        with get_session() as session:
            # 检查账号是否已存在
            existing = session.query(CloudAccount).filter_by(
                cloud_provider=cloud_provider,
                cloud_account=cloud_account
            ).first()
            
            if existing:
                self.logger.warning(f"账号已存在: {cloud_account}")
                return None
            
            # 创建新账号
            account = CloudAccount(
                cloud_provider=cloud_provider,
                cloud_account=cloud_account,
                cloud_password=cloud_password,
                display_name=display_name or cloud_account
            )
            
            session.add(account)
            session.commit()
            
            # 获取账号ID后重新查询，避免会话分离问题
            account_id = account.id
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            
            self.logger.info(f"添加云盘账号成功: {cloud_account}")
            return account
    
    def remove_cloud_account(self, account_id: int) -> bool:
        """删除云盘账号
        
        Args:
            account_id: 账号ID
        
        Returns:
            是否删除成功
        """
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                self.logger.warning(f"账号不存在: {account_id}")
                return False
            
            # 检查是否有关联的文件
            from webdav.models import VirtualFile
            file_count = session.query(VirtualFile).filter_by(account_id=account_id).count()
            if file_count > 0:
                self.logger.warning(f"账号 {account_id} 还有 {file_count} 个关联文件，无法删除")
                return False
            
            session.delete(account)
            session.commit()
            
            self.logger.info(f"删除云盘账号成功: {account.cloud_account}")
            return True
    
    def update_cloud_account(self, account_id: int, **kwargs) -> bool:
        """更新云盘账号信息
        
        Args:
            account_id: 账号ID
            **kwargs: 要更新的字段
        
        Returns:
            是否更新成功
        """
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                self.logger.warning(f"账号不存在: {account_id}")
                return False
            
            # 更新字段
            for key, value in kwargs.items():
                if hasattr(account, key):
                    setattr(account, key, value)
            
            account.updated_at = datetime.utcnow()
            session.commit()
            
            self.logger.info(f"更新云盘账号成功: {account.cloud_account}")
            return True
    
    def get_cloud_account(self, account_id: int) -> Optional[CloudAccount]:
        """获取云盘账号信息
        
        Args:
            account_id: 账号ID
        
        Returns:
            账号对象，不存在返回None
        """
        with get_session() as session:
            return session.query(CloudAccount).filter_by(id=account_id).first()
    
    def list_cloud_accounts(self, active_only: bool = True) -> List[Dict[str, Any]]:
        """获取云盘账号列表
        
        Args:
            active_only: 是否只返回活跃账号
        
        Returns:
            账号字典列表
        """
        with get_session() as session:
            query = session.query(CloudAccount)
            if active_only:
                query = query.filter_by(is_active=True)
            
            accounts = query.order_by(CloudAccount.created_at).all()
            # 转换为字典以避免会话分离问题
            result = []
            for account in accounts:
                result.append({
                    'id': account.id,
                    'cloud_provider': account.cloud_provider,
                    'cloud_account': account.cloud_account,
                    'display_name': account.display_name,
                    'is_active': account.is_active,
                    'created_at': account.created_at,
                    'updated_at': account.updated_at
                })
            return result
    
    def test_cloud_account(self, account_id: int) -> Dict[str, Any]:
        """测试云盘账号连接
        
        Args:
            account_id: 账号ID
        
        Returns:
            测试结果
        """
        account = self.get_cloud_account(account_id)
        if not account:
            return {
                'success': False,
                'error': '账号不存在'
            }
        
        try:
            # 尝试获取客户端
            client = tianyi_integration.get_client(account_id)
            if not client:
                return {
                    'success': False,
                    'error': '无法创建客户端'
                }
            
            # 测试登录状态
            if hasattr(client, 'check_login_status'):
                login_status = client.check_login_status()
                if login_status:
                    return {
                        'success': True,
                        'message': '账号连接正常'
                    }
                else:
                    return {
                        'success': False,
                        'error': '登录状态无效'
                    }
            else:
                return {
                    'success': True,
                    'message': '客户端创建成功（无法验证登录状态）'
                }
        
        except Exception as e:
            self.logger.error(f"测试账号连接失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_account_stats(self, account_id: int) -> Dict[str, Any]:
        """获取账号统计信息
        
        Args:
            account_id: 账号ID
        
        Returns:
            统计信息
        """
        with get_session() as session:
            account = session.query(CloudAccount).filter_by(id=account_id).first()
            if not account:
                return {}
            
            from webdav.models import VirtualFile, VirtualStorage
            
            # 统计关联的文件数量
            file_count = session.query(VirtualFile).filter_by(account_id=account_id).count()
            
            # 统计存储大小
            total_size = session.query(VirtualStorage).join(VirtualFile).filter(
                VirtualFile.account_id == account_id
            ).with_entities(VirtualStorage.size).all()
            
            total_size = sum(size[0] for size in total_size if size[0])
            
            return {
                'account_id': account_id,
                'cloud_account': account.cloud_account,
                'display_name': account.display_name,
                'is_active': account.is_active,
                'file_count': file_count,
                'total_size': total_size,
                'created_at': account.created_at,
                'updated_at': account.updated_at
            }
    
    def set_account_status(self, account_id: int, is_active: bool) -> bool:
        """设置账号状态
        
        Args:
            account_id: 账号ID
            is_active: 是否激活
        
        Returns:
            是否设置成功
        """
        return self.update_cloud_account(account_id, is_active=is_active)
    
    def add_webdav_user(self, username: str, password: str, root_path: str = '/', 
                       can_read: bool = True, can_write: bool = True, 
                       can_delete: bool = True) -> Optional[WebDAVUser]:
        """添加WebDAV用户
        
        Args:
            username: 用户名
            password: 密码
            root_path: 根路径
            can_read: 是否可读
            can_write: 是否可写
            can_delete: 是否可删除
        
        Returns:
            创建的用户对象，失败返回None
        """
        with get_session() as session:
            # 检查用户是否已存在
            existing = session.query(WebDAVUser).filter_by(username=username).first()
            if existing:
                self.logger.warning(f"用户已存在: {username}")
                return None
            
            # 创建新用户（使用快速哈希提高性能）
            user = WebDAVUser(
                username=username,
                password_hash=WebDAVUser.hash_password(password, use_fast_hash=True),
                root_path=root_path,
                can_read=can_read,
                can_write=can_write,
                can_delete=can_delete
            )
            
            session.add(user)
            session.commit()
            session.refresh(user)
            
            self.logger.info(f"添加WebDAV用户成功: {username}")
            return user
    
    def remove_webdav_user(self, user_id: int) -> bool:
        """删除WebDAV用户
        
        Args:
            user_id: 用户ID
        
        Returns:
            是否删除成功
        """
        with get_session() as session:
            user = session.query(WebDAVUser).filter_by(id=user_id).first()
            if not user:
                self.logger.warning(f"用户不存在: {user_id}")
                return False
            
            session.delete(user)
            session.commit()
            
            self.logger.info(f"删除WebDAV用户成功: {user.username}")
            return True
    
    def list_webdav_users(self, active_only: bool = True) -> List[Dict[str, Any]]:
        """获取WebDAV用户列表
        
        Args:
            active_only: 是否只返回活跃用户
        
        Returns:
            用户字典列表
        """
        with get_session() as session:
            query = session.query(WebDAVUser)
            if active_only:
                query = query.filter_by(is_active=True)
            
            users = query.order_by(WebDAVUser.created_at).all()
            # 转换为字典以避免会话分离问题
            result = []
            for user in users:
                result.append({
                    'id': user.id,
                    'username': user.username,
                    'root_path': user.root_path,
                    'can_read': user.can_read,
                    'can_write': user.can_write,
                    'can_delete': user.can_delete,
                    'is_active': user.is_active,
                    'created_at': user.created_at,
                    'updated_at': user.updated_at
                })
            return result
    
    def update_webdav_user_password(self, user_id: int, new_password: str) -> bool:
        """更新WebDAV用户密码
        
        Args:
            user_id: 用户ID
            new_password: 新密码
        
        Returns:
            是否更新成功
        """
        with get_session() as session:
            user = session.query(WebDAVUser).filter_by(id=user_id).first()
            if not user:
                self.logger.warning(f"用户不存在: {user_id}")
                return False
            
            user.password_hash = WebDAVUser.hash_password(new_password, use_fast_hash=True)
            user.updated_at = datetime.utcnow()
            session.commit()
            
            self.logger.info(f"更新WebDAV用户密码成功: {user.username}")
            return True

# 全局实例
account_manager = AccountManager()